<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="菜单名称" prop="menuNameLike">
        <el-input
          v-model="queryParams.menuNameLike"
          placeholder="请输入菜单名称"
          clearable
          size="default"
          @keyup.enter="handleQuery"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="菜单状态" prop="visible">
        <el-select v-model="queryParams.visible" placeholder="菜单状态" clearable size="default" style="width: 240px">
          <el-option
            v-for="dict in visibleOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="default" style="width: 240px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['system:menu:search']" />
        <reset-button @click="resetQuery" :perm="['system:menu:search']" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['system:menu:insert']" :roleType="['conf']" />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['system:menu:search']"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="menuId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="menuName"
        label="菜单名称"
        :show-overflow-tooltip="true"
        min-width="180"
      >
        <template #default="scope">
          <svg-icon :icon-class="scope.row.icon" class="mr10" />
          <span>{{ scope.row.menuName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="menuType" label="类型" align="center" width="80">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.menuType === 'M'">目录</el-tag>
          <el-tag type="success" v-else-if="scope.row.menuType === 'C'">菜单</el-tag>
          <el-tag type="warning" v-else-if="scope.row.menuType === 'F'">按钮</el-tag>
          <span v-else>{{ scope.row.menuType }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="path"
        label="路由地址"
        align="center"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        prop="component"
        label="组件路径"
        align="center"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column
        prop="perms"
        label="权限标识"
        align="center"
        :show-overflow-tooltip="true"
        min-width="120"
      />
      <el-table-column prop="alwaysShow" label="始终显示" align="center" width="80">
        <template #default="scope">
          <span :class="scope.row.alwaysShow === 'N' ? 'text-danger' : ''">{{
            selectDictLabel(alwaysShowOptions, scope.row.alwaysShow)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="visible" label="菜单状态" align="center" width="80">
        <template #default="scope">
          <span :class="scope.row.visible === 'N' ? 'text-danger' : ''">{{
            selectDictLabel(visibleOptions, scope.row.visible)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80">
        <template #default="scope">
          <span :class="scope.row.status === 'N' ? 'text-danger' : ''">{{
            selectDictLabel(statusOptions, scope.row.status)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center" width="60" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        v-if="hasRoleType(['conf'])"
      >
        <template #default="scope">
          <text-add-button
            @click="handleAdd(scope.row)"
            :perm="['system:menu:insert']"
            :roleType="['conf']"
          />
          <text-edit-button
            @click="handleUpdate(scope.row)"
            :perm="['system:menu:update']"
            :roleType="['conf']"
          />
          <text-delete-button
            @click="handleDelete(scope.row)"
            :perm="['system:menu:delete']"
            :roleType="['conf']"
            :title="'是否确认删除' + scope.row.menuName + '?'"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select v-model="form.parentId" :data="menuOptions" check-strictly
                :render-after-expand="false" :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
                placeholder="选择上级菜单" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
              <icon-select ref="iconSelect" v-model="form.icon" />
              <!-- <el-popover placement="bottom-start" width="460" trigger="click">
                  <template #reference>
                    <el-input v-model="form.icon" placeholder="点击选择图标" readonly>
                    <template #prefix>
                        <svg-icon v-if="form.icon" :icon-class="form.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
                        <el-icon v-else>
                            <Search />
                        </el-icon>
                    </template>
                  </el-input>
                  </template>
                </el-popover> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio value="Y">是</el-radio>
                <el-radio value="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'M'" label="权限标识">
              <el-input v-model="form.perms" placeholder="请权限标识" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio
                  v-for="dict in visibleOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="始终显示">
              <el-radio-group v-model="form.alwaysShow">
                <el-radio
                  v-for="dict in alwaysShowOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label-width="95px" label="是否为Anvil">
              <el-radio-group v-model="form.isAnvil">
                <el-radio
                    v-for="dict in alwaysShowOptions"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType === 'C'" label-width="110px" label="批量增加按钮">
              <AddButton @click="addButtonShow = true"></AddButton>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统标识">
              <el-select
                v-model="form.appKey"
                multiple
                placeholder="请选择系统标识"
                :clearable="true"
                style="width: 100%"
              >
                <el-option
                  v-for="item in appKeyOptions"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单分组">
              <el-select
                v-model="form.menuGroup"
                multiple
                placeholder="请选择菜单分组"
                :clearable="true"
                style="width: 100%"
              >
                <el-option
                  v-for="item in menuGroupOptions"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>

    <!-- 批量增加按钮对话框 -->
    <drag-dialog
      v-model="addButtonShow"
      width="400px"
      title="批量增加按钮"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="button in buttonList"
                     :label="button.name"
                     :value="button"
                     :key="button.id"
        >{{ button.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <dialog-footer @ok="submitAddButton" @cancel="cancelAddButton" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu } from '@base/api/base/menu'
import { IconSelect } from '@/components/IconSelect'
import AddButton from "@/components/Zmids/Buttons/AddButton.vue";
import DialogFooter from "@/components/Zmids/DialogFooter/index.vue";

export default {
  name: 'BaseMenu',
  components: {DialogFooter, AddButton, IconSelect },
  data() {
    return {
      // 系统标识下拉数组
      appKeyOptions:[],
      // 菜单分组下拉数组
      menuGroupOptions:[],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      // 始终显示数据字典
      alwaysShowOptions: [],
      // 是否显示批量新增按钮菜单
      addButtonShow: false,
      isIndeterminate: true,
      // 是否全选按钮
      checkAll: false,
      // 选中按钮菜单
      checkedCities: [],
      // 按钮列表
      buttonList: [
        {id: 1, name: '增加', value:'insert'},
        {id: 2, name: '删除', value:'delete'},
        {id: 3, name: '修改', value:'update'},
        {id: 4, name: '查询', value:'select'},
        {id: 5, name: '导入', value:'import'},
        {id: 6, name: '导出', value:'export'},
        {id: 7, name: '启用', value:'enable'},
        {id: 8, name: '禁用', value:'disable'},
       ],
      // 查询参数
      queryParams: {
        menuNameLike: undefined,
        visible: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
        path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_show_hide').then((response) => {
      this.visibleOptions = response.data
    })
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_yes_no').then((response) => {
      this.alwaysShowOptions = response.data
    })
    this.getDicts('sys_app_key').then((response) => {
      this.appKeyOptions = response.data
    })
    this.getDicts('sys_menu_group').then((response) => {
      this.menuGroupOptions = response.data
    })
  },
  methods: {
    // 选择图标
    selected(name) {
      this.form.icon = name
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true
      listMenu(this.queryParams).then((response) => {
        this.menuList = this.handleTree(response.data, 'menuId')
        this.loading = false
      })
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then((response) => {
        this.menuOptions = []
        const menu = { menuId: 0, menuName: '所有菜单', children: [] }
        menu.children = this.handleTree(response.data, 'menuId')
        this.menuOptions.push(menu)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.resetButtonList()
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: 'M',
        orderNum: 1,
        isFrame: 'N',
        visible: 'Y',
        status: 'Y'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.resetButtonList()
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId
      } else {
        this.form.parentId = 0
      }
      this.open = true
      this.title = '添加菜单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      getMenu(row.menuId).then((response) => {
        this.form = response.data
        this.form.appKey = response.data.appKey == null ? null : response.data.appKey.split(',')
        this.form.menuGroup = response.data.menuGroup == null ? null : response.data.menuGroup.split(',')
        if(this.form.parentId && this.form.parentId == '0'){
          this.form.parentId = 0
        }
        this.open = true
        this.title = '修改菜单'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.checkedCities && this.checkedCities.length > 0){
            // 处理按钮权限标识
            this.handleAddButtonList()
            // 将按钮列表添加到表单中
            this.form.additionalInfo = JSON.stringify(this.checkedCities)
          }
          this.resetButtonList()
          this.form.appKey = this.form.appKey == null ? null : this.form.appKey.join(',')
          this.form.menuGroup = this.form.menuGroup == null ? null : this.form.menuGroup.join(',')
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addMenu(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      delMenu(row.menuId)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    },
    /** 处理按钮列表 */
    handleAddButtonList() {
      let perms = '';
      // 获取权限前缀
      if (this.form.perms != null && this.form.perms !== ''){
        let split = this.form.perms.split(':');
        if (split.length > 1){
          perms = split[0]+":"+split[1]+":"
        }
      }
      if (this.checkedCities.length > 0){
        this.checkedCities.forEach(item =>{
          item.value = perms+item.value;
        })
      }
    },
    /** 全选按钮 */
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.buttonList : [];
      this.isIndeterminate = false;
    },
    /** 处理选中的按钮 */
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.buttonList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.buttonList.length;
    },
    /** 保存新增的按钮 */
    submitAddButton(){
      this.addButtonShow = false;
    },
    /** 取消保存新增的按钮*/
    cancelAddButton(){
      this.resetButtonList()
      this.addButtonShow = false;
    },

    resetButtonList(){
      this.buttonList = [
        {id: 1, name: '增加', value:'insert'},
        {id: 2, name: '删除', value:'delete'},
        {id: 3, name: '修改', value:'update'},
        {id: 4, name: '查询', value:'select'},
        {id: 5, name: '导入', value:'import'},
        {id: 6, name: '导出', value:'export'},
        {id: 7, name: '启用', value:'enable'},
        {id: 8, name: '禁用', value:'disable'},
      ];
      this.checkedCities = [];
    }

  }
}
</script>
